package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<BrandDTO> pageQuery(Integer page, Integer rows,String sortBy,Boolean desc,String key) {

        PageHelper.startPage(page,rows);

        //动态sql生成器，生成的sql语句和Brand相关
        Example example = new Example(Brand.class);

        //判断如果sortBy不为空，则需要在既有的sql尾部拼接orderBy
        if(StringUtils.isNotBlank(sortBy)){
            //setOrderByClause 相当于sql语句中写好了，order by
            example.setOrderByClause(sortBy+(desc ? " DESC":" ASC"));
        }





        //判断key是否为空,如果有值，动态生成sql，可以自己写sql语句
        if (StringUtils.isNotBlank(key)){

            //动态条件拼接工具
            Example.Criteria criteria = example.createCriteria();

            //生成模糊查询 where name like %huawei%
            criteria.andLike("name","%"+key+"%");


            //where letter = h
            criteria.orEqualTo("letter",key);

        }



        //根据动态sql生成器查询
        List<Brand> brands = this.brandMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }

        //基于查询条件去统计总的元素个数，然后根据rows，计算总的页面数

        //自动统计元素个数以及计算总页数
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        //封装分页结果，总元素个数，总页数，以及当前页返回的内容，【brands==>brandDTO】
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getPages(), BeanHelper.copyWithCollection(brands,BrandDTO.class));
    }


    @Transactional
    public void addBrand(BrandDTO brandDTO, List<Long> cids) {


        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);

        int count = 0;

        //保存品牌,并主键回显，只能回显给brand对象
        try {
            count = this.brandMapper.insertSelective(brand);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.DATA_SERVER_DEADE);
        }

        if (1!=count){
            throw new LyException(ExceptionEnum.DATA_SAVE_ERROR);
        }

       //通用mapper，问题在于，只能单表操作，自定义保存分类的方法
        saveCategoryBrand(cids, brand.getId());
    }

    @Transactional
    public void updateBrand(BrandDTO brandDTO, List<Long> cids) {
        Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);

        //通用mapper会自动生成sql，如果不加selective则，生成的sql是对于所有的属性的，但是加了后，那个属性有值，生成的sql才会包含哪个属性，所以相对而言，效率稍高
        int count = this.brandMapper.updateByPrimaryKeySelective(brand);

        if (1!=count){
            throw new LyException(ExceptionEnum.DATA_MODIFY_ERROR);
        }
        //中间表，删除，重建，

        //先统计，当前品牌对应的old分类信息数量
        int categoryCount = this.brandMapper.selectCountCategory(brand.getId());

        int deleteCount = this.brandMapper.deleteCategoryBrand(brand.getId());

        if (categoryCount!=deleteCount){
            throw new LyException(ExceptionEnum.DATA_DELETE_ERROR);
        }

        //重建品牌和分类的关系

        saveCategoryBrand(cids, brand.getId());
    }

    private void saveCategoryBrand(List<Long> cids, Long brandId) {
        int count;
        count = this.brandMapper.insertCategoryBrand(cids, brandId);

        if (count != cids.size()) {
            throw new LyException(ExceptionEnum.DATA_SAVE_ERROR);
        }
    }

    public BrandDTO queryBrandById(Long brandId) {

        Brand brand = this.brandMapper.selectByPrimaryKey(brandId);

        if (brand == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand,BrandDTO.class);
    }

    public List<BrandDTO> queryBrandByCategory(Long cid) {
        List<Brand> brands = this.brandMapper.queryBrandByCategory(cid);

        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }

    public List<BrandDTO> queryBrandByIds(List<Long> ids) {
        List<Brand> brands = this.brandMapper.selectByIdList(ids);

        if (CollectionUtils.isEmpty(brands)){
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(brands,BrandDTO.class);
    }
}
